package server;

import java.io.File;
import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String, HttpServlet> servletMap;

    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap) {
        this.socket = socket;
        this.servletMap = servletMap;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            Server server = ServerLoader.getServer();
            String appBase = server.getAppBase();
            String url = request.getUrl();
            String s = url.replaceAll("/", "\\\\");
            String realFilePath = appBase + s;
            File file = new File(realFilePath);

            if (file.exists() && file.isFile()) {
                // webapps下的静态资源
                response.outputStatic(realFilePath);
            } else if (servletMap.get(url) == null) {
            //     其他静态资源
                response.outputHtml(url);
            } else {
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(url);
                httpServlet.service(request, response);
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}